package zpe.relatorio.web;

import java.io.BufferedOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import zpe.relatorio.model.Extensao;

/**
 * Servlet para impressão do relatório no browser.
 * @author Evandir Rodrigo
 * @since 08/2010
 *
 */
@WebServlet(urlPatterns = {"/report"})
public class WriterReportServlet extends HttpServlet {

    private static final long serialVersionUID = -6222263685880916197L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        BufferedOutputStream bos = null;

        HttpSession session = req.getSession();

        String formato = req.getParameter("formato");

        ServletOutputStream outputStream = resp.getOutputStream();

        if (formato == null) {
            throw new IllegalArgumentException("Formato de relat�rio n�o informado.");
        }

        if (formato.equalsIgnoreCase(Extensao.PDF.name())) {
            resp.setContentType("application/pdf");
        } else if (formato.equalsIgnoreCase(Extensao.HTML.name())) {
            resp.setContentType("text/html");
        } else if (formato.equalsIgnoreCase(Extensao.XLS.name())) {
            resp.setContentType("application/vnd.ms-excel");
        } else if (formato.equalsIgnoreCase(Extensao.ODT.name())) {
            resp.setContentType("application/vnd.oasis.opendocument.text");
        }

        String versionId = req.getParameter("versionId");

        byte[] data = (byte[]) session.getAttribute(versionId);

        if(data == null)
          throw new IllegalArgumentException("Nenhum relatorio foi informado.");

        bos = new BufferedOutputStream(outputStream);

        bos.write(data);

        bos.flush();

        session.removeAttribute(versionId);

        outputStream.flush();
        outputStream.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}
